<?php

namespace App\Http\Controllers\Miniapp;

use App\Http\Controllers\Controller;
use App\Models\miniapp\Setting;
use App\Models\miniapp\User;
use App\Service\MiniappService;

class LoginController extends Controller
{

    /**
     * 通过 code 获取小程序 openid 和 session_key
     * @param {string} $code 小程序登录凭证
     * @return {json}
     */
    public function code($code)
    {
        $res = Setting::whereIn('key', ['appid', 'secret'])->pluck('value', 'key');
        $appid = $res['appid'];
        $secret = $res['secret'];

        [$statusCode, $result] = MiniappService::jscode($appid, $secret, $code);
        if ($statusCode !== 200) return $this->fail($result);

        $openid = $result['openid'];
        $user = User::where(compact('openid'))->first();
        if (!$user) {
            $nickname = 'wx-' . mb_substr($code, 0, 8);
            $avatar = '/storage/uploads/miniapp/default.jpg';  // 默认头像
            $data = compact('openid', 'nickname', 'avatar');
            if (!empty($result['unionid'])) $data['unionid'] = $result['unionid'];
            $user = User::create($data);
        }

        $token = auth('miniapp')->login($user);
        if (!$token) return $this->fail('登录失败');
        $this->recordLogin($user);

        $user->refresh()->load('closest');
        return $this->successful(compact('token', 'user'));
    }


    public function login()
    {
        $openid = request('openid');
        [$code, $user] = $openid ? $this->loginByOpenid($openid) : $this->loginByNormal();

        if ($code === 500) return $this->fail($user);

        $token = auth('miniapp')->login($user);
        if (!$token) return $this->fail('登录失败');

        $this->recordLogin($user);

        $user->refresh()->load('closest');
        return $this->successful(compact('token', 'user'));
    }

    protected function loginByOpenid($openid)
    {
        $user = User::where(compact('openid'))->first();
        if (!$user) return [500, '用户不存在'];
        return [200, $user];
    }

    protected function loginByNormal()
    {
        $username = request('username');
        $password = request('password');
        $user = User::where(compact('username'))->first();
        if (!$user) return [500, '用户不存在'];
        if (!password_verify($password, $user->password)) return [500, '密码错误'];
        return [200, $user];
    }

    protected function recordLogin($user)
    {
        $user->login()->create([
            'login_ip' => request()->ip(),
            'login_at' => now(),
            'device' => request()->server('HTTP_USER_AGENT')
        ]);
    }
}
